﻿/*
helferlein.com ( http://www.helferlein.com )
Michael Tobisch

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions 
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using DotNetNuke.UI.UserControls;
using helferlein.DNN.Modules.Form.Business;
using helferlein.UI.WebControls.Validators;
using helferlein.DNN.Modules.BabelFish.Business;
using helferlein.DNN.Modules.BabelFish.UI;
using DotNetNuke.Security;
using System.Text;
/* The ISearchable Interface was removed in version 2.3.10 as it is no longer supported in the DNN Search infrastructure.
 * It is planned to implement the new (Lucene) search infrastructure in version 3.0.0
using DotNetNuke.Services.Search;
 */

namespace helferlein.DNN.Modules.Form.UI
{
   /// <summary>
   /// Settings for the helferlein_Form module
   /// </summary>
   partial class Settings : ModuleSettingsBase
   {
#region Private Properties
      private ModuleController _controller = null;
      private FormItemController _formController = null;
      private List<FormItemInfo> _theForm = null;
      private BabelFishController _babelFishController = null;
      private PortalSecurity _portalSecurity = null;

      protected ModuleController Controller
      {
         get
         {
            if (_controller == null)
               _controller = new ModuleController();
            return _controller;
         }
      }

      protected FormItemController FormController
      {
         get
         {
            if (_formController == null)
               _formController = new FormItemController();
            return _formController;
         }
      }

      protected List<FormItemInfo> TheForm
      {
         get
         {
            if (_theForm == null)
               _theForm = this.FormController.GetAll(base.ModuleId);
            return _theForm;
         }
      }

      protected string SharedResourceFile
      {
         get { return base.ControlPath + Localization.LocalResourceDirectory + "/" + Localization.LocalSharedResourceFile; }
      }

      protected Dictionary<string, string> GroupOutputByItems
      {
         get
         {
            object o = base.ViewState["GroupOutputByItems"];
            if (o == null)
            {
               Dictionary<string, string> groupOutputByItems = new Dictionary<string, string>();
               foreach (FormItemInfo fii in this.TheForm)
               {
                  if (Helpers.IsItemGroupable(fii.FormItemType))
                  {
                     groupOutputByItems.Add("[FORMITEM]" + Convert.ToString(fii.FormItemID), fii.FormItemLabel);
                  }
               }
               base.ViewState["GroupOutputByItems"] = groupOutputByItems;
            }
            return (Dictionary<string, string>)base.ViewState["GroupOutputByItems"];
         }
      }

      protected Dictionary<string, string> RenderAsHeadlineItems
      {
         get
         {
            object o = base.ViewState["RenderAsHeadLineItems"];
            if (o == null)
            {
               Dictionary<string, string> renderAsHeadlineItems = new Dictionary<string, string>();
               foreach (FormItemInfo fii in this.TheForm)
               {
                  if (Helpers.IsItemRenderableAsHeadline(fii.FormItemType))
                  {
                     renderAsHeadlineItems.Add("[FORMITEM]" + Convert.ToString(fii.FormItemID), fii.FormItemLabel);
                  }
               }
               base.ViewState["RenderAsHeadlineItems"] = renderAsHeadlineItems;
            }
            return (Dictionary<string, string>)base.ViewState["RenderAsHeadlineItems"];
         }
      }

      protected Dictionary<string, string> AddToDropDownListItems
      {
         get
         {
            object o = base.ViewState["AddToDropDownListItems"];
            if (o == null)
            {
               Dictionary<string, string> addToDropDownListItems = new Dictionary<string, string>();
               foreach (FormItemInfo fii in this.TheForm)
               {
                  if (Helpers.IsItemTypeAppendableToDropDownList(fii.FormItemType))
                  {
                     addToDropDownListItems.Add("[FORMITEM]" + Convert.ToString(fii.FormItemID), fii.FormItemLabel);
                  }
               }
               base.ViewState["AddToDropDownListItems"] = addToDropDownListItems;
            }
            return (Dictionary<string, string>)base.ViewState["AddToDropDownListItems"];
         }
      }

      protected BabelFishController BabelFishController
      {
         get
         {
            if (_babelFishController == null)
               _babelFishController = new BabelFishController();
            return _babelFishController;
         }
      }

      protected PortalSecurity PortalSecurity
      {
         get
         {
            if (_portalSecurity == null)
               _portalSecurity = new PortalSecurity();
            return _portalSecurity;
         }
      }
#endregion

#region ML Settings
      protected Dictionary<string, string> Aquarium
      {
         get
         {
            object o = base.ViewState["Aquarium"];
            if (o == null)
               base.ViewState["Aquarium"] = new Dictionary<string, string>();
            return (Dictionary<string, string>)base.ViewState["Aquarium"];
         }
         set { base.ViewState["Aquarium"] = value; }
      }

      protected string ModuleTitle
      {
         get
         {
            string s = String.Empty;
            if (this.Aquarium.TryGetValue("ModuleTitle." + this.LocaleSelector.CurrentLocale, out s))
               return s;
            else
               return String.Empty;
         }
      }

      protected string Subject
      {
         get
         {
            string s = String.Empty;
            if (this.Aquarium.TryGetValue("Subject." + this.LocaleSelector.CurrentLocale, out s))
               return s;
            else
               return String.Empty;
         }
      }
#endregion

#region Submission Settings
      protected bool SubmitByEMail
      {
         get { return Convert.ToBoolean(base.Settings["SubmitByEMail"]); }
         set { this.UpdateBooleanSetting("SubmitByEMail", value); }
      }

      protected bool SaveToDataBase
      {
         get { return Convert.ToBoolean(base.Settings["SaveToDataBase"]); }
         set { this.UpdateBooleanSetting("SaveToDataBase", value); }
      }

      protected string EMailAddress
      {
         get { return Convert.ToString(base.Settings["EMailAddress"]); }
         set { this.UpdateTextSetting("EMailAddress", value); }
      }

      protected MailFormat EMailFormat
      {
         get
         {
            if (base.Settings["EMailFormat"] == null)
               return MailFormat.Text;
            else
               return (MailFormat)Enum.GetValues(typeof(MailFormat)).GetValue(Convert.ToInt32(base.Settings["EMailFormat"]));
         }
         set { this.UpdateIntegerSetting("EMailFormat", Convert.ToInt32(value)); }
      }

      protected string SenderAddress
      {
         get
         {
            object o = base.Settings["SenderAddress"];
            if (o == null)
               return PortalSettings.Email;
            else
               return o.ToString();
         }
         set
         {
            if (value == PortalSettings.Email)
               this.UpdateTextSetting("SenderAddress", null);
            else
               this.UpdateTextSetting("SenderAddress", value);
         }
      }

      protected string ReplyToAddress
      {
         get
         {
            object o = base.Settings["ReplyToAddress"];
            if (o == null)
               return PortalSettings.Email;
            else
               return o.ToString();
         }
         set
         {
            if (value == PortalSettings.Email)
               this.UpdateTextSetting("ReplyToAddress", null);
            else
               this.UpdateTextSetting("ReplyToAddress", value);
         }
      }

      protected bool IncludeIPAddressInEmail
      {
         get { return Convert.ToBoolean(base.Settings["IncludeIPAddressInEmail"]); }
         set { this.UpdateBooleanSetting("IncludeIPAddressInEmail", value); }
      }

      protected string RedirectURL
      {
         get { return Convert.ToString(base.Settings["RedirectURL"]); }
         set { this.UpdateTextSetting("RedirectURL", value); }
      }

      protected string RedirectURLType
      {
         get
         {
            string redirectUrlType = Convert.ToString(base.Settings["RedirectURLType"]);
            if (string.IsNullOrEmpty(redirectUrlType))
               redirectUrlType = "U";
            return redirectUrlType;
         }

         set
         {
            // Due to previous versions where only Urls (Link to external resources) were allowed, "U" is the default...
            if (value == "U")
               this.UpdateTextSetting("RedirectURLType", "");
            else
               this.UpdateTextSetting("RedirectURLType", value);
         }
      }

      protected bool AutoApprove
      {
         get { return Convert.ToBoolean(base.Settings["AutoApprove"]); }
         set { this.UpdateBooleanSetting("AutoApprove", value); }
      }
#endregion

#region Module Appearance Settings
      protected string Theme
      {
         get
         {
            string theme = Convert.ToString(base.Settings["Theme"]);
            // To avoid an error with the "old" theme format up to version 2.2.6
            if (String.IsNullOrEmpty(theme))
               theme = "Default [M]";
            else
            {
               if (!((theme.EndsWith(" [M]")) || (theme.EndsWith(" [P]"))))
                  theme = String.Format("{0} [M]", theme);
            }
            return theme;
         }
         set{ this.UpdateTextSetting("Theme", (value == "Default [M]" ? String.Empty : value)); }
      }
#endregion

#region Form Appearance Settings
      protected Unit? Width
      {
         get { return Unit.Parse(Convert.ToString(base.Settings["Width"])); }
         set { this.UpdateTextSetting("Width", value.ToString()); }
      }

      protected string FormHeaderTemplate
      {
         get { return Server.HtmlDecode(Convert.ToString(base.Settings["FormHeaderTemplate"])); }
         set { this.UpdateTextSetting("FormHeaderTemplate", this.PortalSecurity.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup)); }
      }

      protected string FormItemTemplate
      {
         get { return Server.HtmlDecode(Convert.ToString(base.Settings["FormItemTemplate"])); }
         set { this.UpdateTextSetting("FormItemTemplate", this.PortalSecurity.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup)); }
      }

      protected string FormFooterTemplate
      {
         get { return Server.HtmlDecode(Convert.ToString(base.Settings["FormFooterTemplate"])); }
         set { this.UpdateTextSetting("FormFooterTemplate", this.PortalSecurity.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup)); }
      }

      protected string LabelTemplate
      {
         get { return Server.HtmlDecode(Convert.ToString(base.Settings["LabelTemplate"])); }
         set { this.UpdateTextSetting("LabelTemplate", this.PortalSecurity.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup)); }
      }

      protected int? RequiredFieldMarker
      {
         get
         {
            if (base.Settings["RequiredFieldMarker"] == null)
               return (1);
            else
               return (Convert.ToInt32(base.Settings["RequiredFieldMarker"]));
         }
         set
         {
            if (value > 1)
               this.UpdateIntegerSetting("RequiredFieldMarker", value);
            else
               this.UpdateIntegerSetting("RequiredFieldMarker", null);
         }
      }

      protected ShowAdditionalItems WhereToDisplayRequiredFieldMarkerExplanation
      {
         get
         {
            if (base.Settings["WhereToDisplayRequiredFieldMarkerExplanation"] == null)
               return ShowAdditionalItems.NotAtAll;
            else
               return (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(base.Settings["WhereToDisplayRequiredFieldMarkerExplanation"]) - 1);
         }
         set
         {
            if (value == ShowAdditionalItems.NotAtAll)
               Controller.DeleteModuleSetting(base.ModuleId, "WhereToDisplayRequiredFieldMarkerExplanation");
            else
               Controller.UpdateModuleSetting(base.ModuleId, "WhereToDisplayRequiredFieldMarkerExplanation", Convert.ToInt32(value).ToString());
         }
      }

      protected int? SubmitButtons
      {
         get
         {
            if (base.Settings["SubmitButtons"] == null)
               return (3);
            else
               return (Convert.ToInt32(base.Settings["SubmitButtons"]));
         }
         set
         {
            if (value < 3)
               this.UpdateIntegerSetting("SubmitButtons", value);
            else
               this.UpdateIntegerSetting("SubmitButtons", null);
         }
      }

      protected bool Captcha
      {
         get { return Convert.ToBoolean(base.Settings["Captcha"]); }
         set { this.UpdateBooleanSetting("Captcha", value); }
      }

      protected bool UnauthenticatedUsersOnly
      {
         get { return Convert.ToBoolean(base.Settings["UnauthenticatedUsersOnly"]); }
         set { this.UpdateBooleanSetting("UnauthenticatedUsersOnly", value); }
      }

      protected bool ValidationShowSummary
      {
         get { return Convert.ToBoolean(base.Settings["ValidationShowSummary"]); }
         set { this.UpdateBooleanSetting("ValidationShowSummary", value); }
      }

      protected bool ValidationShowMessageBox
      {
         get { return Convert.ToBoolean(base.Settings["ValidationShowMessageBox"]); }
         set { this.UpdateBooleanSetting("ValidationShowMessageBox", value); }
      }
#endregion

#region Submission Appearance Settings
      protected ShowAdditionalItems WhereToDisplayApprovedSubmissions
      {
         get
         {
            if (base.Settings["WhereToDisplayToDisplayApprovedSubmissions"] == null)
               return ShowAdditionalItems.NotAtAll;
            else
               return (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(base.Settings["WhereToDisplayToDisplayApprovedSubmissions"]) - 1);
         }
         set
         {
            if (value == ShowAdditionalItems.NotAtAll)
               Controller.DeleteModuleSetting(base.ModuleId, "WhereToDisplayToDisplayApprovedSubmissions");
            else
               Controller.UpdateModuleSetting(base.ModuleId, "WhereToDisplayToDisplayApprovedSubmissions", Convert.ToInt32(value).ToString());
         }
      }

      protected int? KeepDays
      {
         get
         {
            int? keepDays = null;
            if (base.Settings["KeepDays"] != null)
               keepDays = Convert.ToInt32(base.Settings["KeepDays"]);
            return keepDays;
         }
         set { this.UpdateIntegerSetting("KeepDays", value); }
      }

      protected string GroupOutputByItem
      {
         get { return (Convert.ToString(base.Settings["GroupOutputBy"])); }
         set { this.UpdateTextSetting("GroupOutputBy", value); }
      }

      protected String RenderAsHeadlineItem
      {
         get { return (Convert.ToString(base.Settings["RenderAsHeadline"])); }
         set { this.UpdateTextSetting("RenderAsHeadline", value); }
      }

      protected bool UseHeadlineAsSubject
      {
         get { return (Convert.ToBoolean(base.Settings["UseHeadlineAsSubject"])); }
         set { this.UpdateBooleanSetting("UseHeadlineAsSubject", value); }
      }

      protected String HeadlineAlignment
      {
         get
         {
            if (base.Settings["HeadlineAlignment"] == null)
               return "Left";
            else
               return (Convert.ToString(base.Settings["HeadlineAlignment"]));
         }
         set { this.UpdateTextSetting("HeadlineAlignment", value); }
      }

      protected bool ShowDate
      {
         get { return Convert.ToBoolean(base.Settings["ShowDate"]); }
         set { this.UpdateBooleanSetting("ShowDate", value); }
      }

      protected bool ShowFlag
      {
         get { return Convert.ToBoolean(base.Settings["ShowFlag"]); }
         set { this.UpdateBooleanSetting("ShowFlag", value); }
      }

      private bool ShowLabels
      {
         get { return Convert.ToBoolean(base.Settings["ShowLabels"]); }
         set { this.UpdateBooleanSetting("ShowLabels", value); }
      }

      private bool ShowRecipient
      {
         get { return Convert.ToBoolean(base.Settings["ShowRecipient"]); }
         set { this.UpdateBooleanSetting("ShowRecipient", value); }
      }
#endregion

#region Edit Submission Settings
      protected string AddToDropDownListItem
      {
         get { return (Convert.ToString(base.Settings["AddToDropDownList"])); }
         set { this.UpdateTextSetting("AddToDropDownList", value); }
      }
#endregion

/* The ISearchable Interface was removed in version 2.3.10 as it is no longer supported in the DNN Search infrastructure.
   * It is planned to implement the new (Lucene) search infrastructure in version 3.0.0
   */
#region Other Settings
      protected bool IncludeMailAddressesInSearch
      {
         get { return false; }
         set { this.UpdateBooleanSetting("IncludeMailAddressesInSearch", false); }
      }
#endregion

#region Event Handlers
      protected void ResetFormHeaderTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink resetFormHeaderTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("ResetFormHeaderTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function ResetFormHeaderTemplate_ClientClick() {");
            scriptBuilder.Append("var headerTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormHeaderTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("headerTemplateTextBox.value = \"");
            scriptBuilder.Append(this.FormHeaderTemplate.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "ResetFormHeaderTemplate", scriptBuilder.ToString(), true);
         }
         resetFormHeaderTemplateHyperLink.NavigateUrl = "javascript:ResetFormHeaderTemplate_ClientClick();";
      }

      protected void SetDefaultFormHeaderTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink setDefaultFormHeaderTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("SetDefaultFormHeaderTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function SetDefaultFormHeaderTemplate_ClientClick() {");
            scriptBuilder.Append("var headerTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormHeaderTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("headerTemplateTextBox.value = \"");
            scriptBuilder.Append(Base.DEFAULT_FORM_HEADER_TEMPLATE.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "SetDefaultFormHeaderTemplate", scriptBuilder.ToString(), true);
         }
         setDefaultFormHeaderTemplateHyperLink.NavigateUrl = "javascript:SetDefaultFormHeaderTemplate_ClientClick();";
      }

      protected void ResetFormItemTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink resetFormItemTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("ResetFormItemTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function ResetFormItemTemplate_ClientClick() {");
            scriptBuilder.Append("var itemTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormItemTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("itemTemplateTextBox.value = \"");
            scriptBuilder.Append(this.FormItemTemplate.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "ResetFormItemTemplate", scriptBuilder.ToString(), true);
         }
         resetFormItemTemplateHyperLink.NavigateUrl = "javascript:ResetFormItemTemplate_ClientClick();";
      }

      protected void SetDefaultFormItemTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink setDefaultFormItemTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("SetDefaultFormItemTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function SetDefaultFormItemTemplate_ClientClick() {");
            scriptBuilder.Append("var itemTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormItemTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("itemTemplateTextBox.value = \"");
            scriptBuilder.Append(Base.DEFAULT_FORM_ITEM_TEMPLATE.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "SetDefaultFormItemTemplate", scriptBuilder.ToString(), true);
         }
         setDefaultFormItemTemplateHyperLink.NavigateUrl = "javascript:SetDefaultFormItemTemplate_ClientClick();";
      }

      protected void ResetFormFooterTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink resetFormFooterTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("ResetFormFooterTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function ResetFormFooterTemplate_ClientClick() {");
            scriptBuilder.Append("var footerTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormFooterTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("footerTemplateTextBox.value = \"");
            scriptBuilder.Append(this.FormFooterTemplate.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "ResetFormFooterTemplate", scriptBuilder.ToString(), true);
         }
         resetFormFooterTemplateHyperLink.NavigateUrl = "javascript:ResetFormFooterTemplate_ClientClick();";
      }

      protected void SetDefaultFormFooterTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink setDefaultFormFooterTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("SetDefaultFormFooterTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function SetDefaultFormFooterTemplate_ClientClick() {");
            scriptBuilder.Append("var footerTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.FormFooterTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("footerTemplateTextBox.value = \"");
            scriptBuilder.Append(Base.DEFAULT_FORM_FOOTER_TEMPLATE.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "SetDefaultFormFooterTemplate", scriptBuilder.ToString(), true);
         }
         setDefaultFormFooterTemplateHyperLink.NavigateUrl = "javascript:SetDefaultFormFooterTemplate_ClientClick();";
      }

      protected void ResetFormLabelTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink resetFormLabelTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("ResetFormLabelTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function ResetFormLabelTemplate_ClientClick() {");
            scriptBuilder.Append("var labelTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.LabelTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("labelTemplateTextBox.value = \"");
            scriptBuilder.Append(this.LabelTemplate.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "ResetFormLabelTemplate", scriptBuilder.ToString(), true);
         }
         resetFormLabelTemplateHyperLink.NavigateUrl = "javascript:ResetFormLabelTemplate_ClientClick();";
      }

      protected void SetDefaultFormLabelTemplateHyperLink_Load(object sender, EventArgs e)
      {
         HyperLink setDefaultFormLabelTemplateHyperLink = (HyperLink)sender;
         if (!(base.Page.ClientScript.IsClientScriptBlockRegistered("SetDefaultFormLabelTemplate")))
         {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append("function SetDefaultFormLabelTemplate_ClientClick() {");
            scriptBuilder.Append("var labelTemplateTextBox = document.getElementById(\"");
            scriptBuilder.Append(this.LabelTemplateTextBox.ClientID);
            scriptBuilder.Append("\");");
            scriptBuilder.Append("labelTemplateTextBox.value = \"");
            scriptBuilder.Append(Base.DEFAULT_FORM_LABEL_TEMPLATE.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r"));
            scriptBuilder.Append("\";");
            scriptBuilder.Append("}");
            base.Page.ClientScript.RegisterClientScriptBlock(base.Page.GetType(), "SetDefaultFormLabelTemplate", scriptBuilder.ToString(), true);
         }
         setDefaultFormLabelTemplateHyperLink.NavigateUrl = "javascript:SetDefaultFormLabelTemplate_ClientClick();";
      }

      protected override void OnInit(EventArgs e)
      {
         this.LocaleSelector.SelectedIndexChanged += new EventHandler(LocaleSelector_SelectedIndexChanged);
         this.LocaleSelector.UpdateRequested += new EventHandler(this.LocaleSelector_UpdateRequested);
         base.OnInit(e);
      }

      public override void LoadSettings()
      {
         // Load the form
         try
         {
            if (!(Page.IsPostBack))
            {
               List<BabelFishInfo> aquarium = this.BabelFishController.GetStrings(base.PortalId, "helferlein.Form.Settings." + Convert.ToString(base.ModuleId).Trim());
               if (aquarium != null)
                  foreach (BabelFishInfo fish in aquarium)
                     this.Aquarium.Add(fish.StringKey + "." + fish.Locale, fish.StringText);
            }
         }
         catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         if (!(Page.IsPostBack))
         {
            if (!(this.LocaleSelector.Visible))
               this.MultiLingualSettingsHead.IsExpanded = true;
         }
      }

      public override void UpdateSettings()
      {
         if (Page.IsValid)
         {
            try
            {
               // MULTI LINGUAL SETTING
               this.UpdateAquarium(this.LocaleSelector.CurrentLocale);
               // This is because of the business rule that the deletion of a fallback value is not allowed when another value exists.
               // So first, handle the non-fallback strings...
               foreach (KeyValuePair<string, string> fish in this.Aquarium)
               {
                  string locale = fish.Key.Substring(fish.Key.LastIndexOf('.') + 1);
                  if (locale != PortalSettings.DefaultLanguage)
                  {
                     if (!(String.IsNullOrEmpty(fish.Value)))
                        this.BabelFishController.Change(base.PortalId, locale, "helferlein.Form.Settings." + base.ModuleId.ToString(), fish.Key.Substring(0, fish.Key.LastIndexOf('.')), fish.Value);
                     else
                        this.BabelFishController.Drop(base.PortalId, locale, "helferlein.Form.Settings." + base.ModuleId.ToString(), fish.Key.Substring(0, fish.Key.LastIndexOf('.')));
                  }
               }
               // ... and the handle the portal's default language
               foreach (KeyValuePair<string, string> fish in this.Aquarium)
               {
                  string locale = fish.Key.Substring(fish.Key.LastIndexOf('.') + 1);
                  if (locale == PortalSettings.DefaultLanguage)
                  {
                     if (!(String.IsNullOrEmpty(fish.Value)))
                        this.BabelFishController.Change(base.PortalId, locale, "helferlein.Form.Settings." + base.ModuleId.ToString(), fish.Key.Substring(0, fish.Key.LastIndexOf('.')), fish.Value);
                     else
                        this.BabelFishController.Drop(base.PortalId, locale, "helferlein.Form.Settings." + base.ModuleId.ToString(), fish.Key.Substring(0, fish.Key.LastIndexOf('.')));
                  }
               }

               // SUBMISSION SETTINGS
               // Send Mode
               this.SubmitByEMail = this.SendModes.Items[0].Selected;
               this.SaveToDataBase = this.SendModes.Items[1].Selected;
               // Email Address
               // if (this.SubmitByEMail) <---- Don't know why this is not working...
               if (this.SendModes.Items[0].Selected)
                  this.EMailAddress = this.EMailAddressTextBox.Text;
               else
                  this.EMailAddress = String.Empty;

               // Subject
               // this.Subject = this.SubjectTextBox.Text;
               // Redirect Url
               this.RedirectURLType = this.RedirectURLControl.UrlType;
               this.RedirectURL = this.RedirectURLControl.Url;
               // Approval
               this.AutoApprove = this.AutoApproveCheckBox.Checked;

               // EMAIL OPTIONS
               // Email Format
               this.EMailFormat = (this.EMailFormatCheckBox.Checked ? MailFormat.Html : MailFormat.Text);
               // Sender
               if (this.SenderAddressDropDownList.Visible)
               {
                  this.SenderAddress = this.SenderAddressDropDownList.SelectedValue;
                  if (this.SenderAddress.StartsWith("[FORMITEM]"))
                  {
                     // This is an e-mail address form item. Ensure it is required!
                     this.FormController.RequireItem(Convert.ToInt32(this.SenderAddress.Substring(10)));
                  }
               }
               else
                  this.SenderAddress = null;
               // ReplyTo
               if (this.ReplyToAddressDropDownList.Visible)
               {
                  this.ReplyToAddress = this.ReplyToAddressDropDownList.SelectedValue;
                  if (this.ReplyToAddress.StartsWith("[FORMITEM]"))
                  {
                     // This is an e-mail address form item. Ensure it is required!
                     this.FormController.RequireItem(Convert.ToInt32(this.ReplyToAddress.Substring(10)));
                  }
               }
               else
                  this.ReplyToAddress = null;
               // Include IP Address
               this.IncludeIPAddressInEmail = this.IncludeIPAddressInEmailCheckBox.Checked;

               // MODULE APPEARANCE
               // Theme
               this.Theme = this.ThemeDropDownList.SelectedValue;

               // FORM APPEARANCE
               // Width
               this.Width = this.UnitParser(this.WidthTextBox.Text);
               // Form Header Template
               if (this.FormHeaderTemplateTextBox.Text != Base.DEFAULT_FORM_HEADER_TEMPLATE)
                  this.FormHeaderTemplate = this.FormHeaderTemplateTextBox.Text;
               else
                  this.FormHeaderTemplate = String.Empty;
               // Form ItemTemplate
               if (this.FormItemTemplateTextBox.Text != Base.DEFAULT_FORM_ITEM_TEMPLATE)
                  this.FormItemTemplate = this.FormItemTemplateTextBox.Text;
               else
                  this.FormItemTemplate = String.Empty;
               // Form Footer Template
               if (this.FormFooterTemplateTextBox.Text != Base.DEFAULT_FORM_FOOTER_TEMPLATE)
                  this.FormFooterTemplate = this.FormFooterTemplateTextBox.Text;
               else
                  this.FormFooterTemplate = String.Empty;
               // Label Template
               if (this.LabelTemplateTextBox.Text != Base.DEFAULT_FORM_LABEL_TEMPLATE)
                  this.LabelTemplate = this.LabelTemplateTextBox.Text;
               else
                  this.LabelTemplate = String.Empty;
               // Required Field Marker
               this.RequiredFieldMarker = Convert.ToInt32(this.RequiredFieldMarkerOptions.SelectedValue);
               // Required Field Marker Explanation
               this.WhereToDisplayRequiredFieldMarkerExplanation = (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(this.ShowRequiredFieldMarkerExplanationOptions.SelectedValue) - 1);
               // Buttons
               this.SubmitButtons = Convert.ToInt32(this.SubmitButtonOptions.SelectedValue);
               // Options: Captcha
               this.Captcha = this.CaptchaCheckBox.Checked;
               this.UnauthenticatedUsersOnly = this.UnauthenticatedUsersOnlyCheckBox.Checked;
               // ValidationSummary
               this.ValidationShowSummary = this.ValidationDisplays.Items[0].Selected;
               this.ValidationShowMessageBox = this.ValidationDisplays.Items[1].Selected;

               // SUBMISSION APPEARANCE
               // Where display submissions
               this.WhereToDisplayApprovedSubmissions = (ShowAdditionalItems)Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(Convert.ToInt32(this.ShowApprovedSubmissionsOptions.SelectedValue) - 1);
               // Keep for days
               this.KeepDays = this.Int32Parser(this.KeepDaysTextBox.Text);
               // Group output by
               if (this.GroupOutputByDropDownList.Visible)
                  this.GroupOutputByItem = this.GroupOutputByDropDownList.SelectedValue;
               else
                  this.GroupOutputByItem = null;
               // Render as headline
               if (this.RenderAsHeadlineDropDownList.Visible)
               {
                  this.RenderAsHeadlineItem = this.RenderAsHeadlineDropDownList.SelectedValue;
                  if (UseHeadlineAsSubjectPanel.Visible)
                     this.UseHeadlineAsSubject = this.UseHeadlineAsSubjectCheckBox.Checked;
                  else
                     this.UseHeadlineAsSubject = false;
               }
               else
               {
                  this.RenderAsHeadlineItem = null;
                  this.UseHeadlineAsSubject = false;
               }
               // Headline alignment
               this.HeadlineAlignment = this.HeadlineAlignmentRadioButtonList.SelectedValue;
               // Options: Date, flag, labels, recipient
               this.ShowDate = this.ShowDateCheckBox.Checked;
               this.ShowFlag = this.ShowFlagCheckBox.Checked;
               this.ShowLabels = this.ShowLabelsCheckBox.Checked;
               this.ShowRecipient = this.ShowRecipientCheckBox.Checked;

               // EDIT SUBMISSIONS SETTINGS
               // Add to DropDownList
               if (this.AddToDropDownListDropDownList.Visible)
                  this.AddToDropDownListItem = this.AddToDropDownListDropDownList.SelectedValue;
               else
                  this.AddToDropDownListItem = null;

               // OTHER SETTINGS
               /* The ISearchable Interface was removed in version 2.3.10 as it is no longer supported in the DNN Search infrastructure.
                * It is planned to implement the new (Lucene) search infrastructure in version 3.0.0
               // Include E-Mail addresses in search
               if (this.IncludeMailAddressesInSearch != this.IncludeMailAddressesInSearchCheckBox.Checked)
               {
                  // when the value has changed, then delete all search items from this module
                  // DotNetNuke.Data.DataProvider.Instance().DeleteSearchItems(base.ModuleId);
                  Dictionary<string, SearchItemInfo> oldSearchItems = SearchDataStoreController.GetSearchItems(base.ModuleId);
                  foreach (KeyValuePair<string, SearchItemInfo> oldSearchItem in oldSearchItems)
                  {
                     SearchDataStoreController.DeleteSearchItem(oldSearchItem.Value.SearchItemId);
                  }

                  // and reindex the content??
                  // new DotNetNuke.Services.Search.SearchEngine().IndexContent(base.PortalId);
               }
                */
               // this.IncludeMailAddressesInSearch = this.IncludeMailAddressesInSearchCheckBox.Checked;
               this.IncludeMailAddressesInSearch = false;

               Response.Redirect(Globals.NavigateURL(), false);
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void LocaleSelector_SelectedIndexChanged(object sender, EventArgs e)
      {
         this.ModuleTitleTextBox.Text = this.ModuleTitle;
         this.SubjectTextBox.Text = this.Subject;
      }

      protected void LocaleSelector_UpdateRequested(object sender, EventArgs e)
      {
         LocaleSelector localeSelector = (LocaleSelector)sender;
         this.UpdateAquarium(localeSelector.ProcessedLocale);
      }

      protected void ModuleTitleTextBox_Load(object sender, EventArgs e)
      {
         TextBox moduleTitleTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            BabelFishInfo moduleTitle = this.BabelFishController.GetString(base.PortalId, this.LocaleSelector.CurrentLocale, "helferlein.Form.Settings." + base.ModuleId, "ModuleTitle");
            if (moduleTitle != null)
            {
               moduleTitleTextBox.Text = moduleTitle.StringText;
            }
         }
      }

      protected void SubjectTextBox_Load(object sender, EventArgs e)
      {
         TextBox subjectTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            BabelFishInfo subject = this.BabelFishController.GetString(base.PortalId, this.LocaleSelector.CurrentLocale, "helferlein.Form.Settings." + base.ModuleId, "Subject");
            if (subject != null)
            {
               subjectTextBox.Text = subject.StringText;
            }
         }
      }

      protected void SendModes_Load(object sender, EventArgs e)
      {
         CheckBoxList sendModes = (CheckBoxList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               // E-Mail:
               sendModes.Items[0].Text = Localization.GetString("EmailCheckBox.Text", base.LocalResourceFile);
               sendModes.Items[0].Selected = this.SubmitByEMail;
               // Database:
               sendModes.Items[1].Text = Localization.GetString("DatabaseCheckBox.Text", base.LocalResourceFile);
               sendModes.Items[1].Selected = this.SaveToDataBase;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void SendModes_SelectedIndexChanged(object sender, EventArgs e)
      {
         CheckBoxList sendModes = (CheckBoxList)sender;
         try
         {
            this.EMailAddressValidator.Required = sendModes.Items[0].Selected;
            this.UseHeadlineAsSubjectPanel.Visible = ((this.RenderAsHeadlineItems.Count > 0) && (this.RenderAsHeadlineDropDownList.SelectedIndex > 0) && (sendModes.Items[0].Selected));
         }
         catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
      }

      protected void SendModesValidator_Load(object sender, EventArgs e)
      {
         CheckBoxListValidator sendModesValidator = (CheckBoxListValidator)sender;
         if (!(Page.IsPostBack))
         {
            try { sendModesValidator.ErrorMessage = Localization.GetString("SendModesValidator.ErrorMessage", base.LocalResourceFile); }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void EMailAddressTextBox_Load(object sender, EventArgs e)
      {
         TextBox eMailAddressTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { eMailAddressTextBox.Text = this.EMailAddress; }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void EMailAddressValidator_Load(object sender, EventArgs e)
      {
         RegExpValidator eMailAddressValidator = (RegExpValidator)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               StringBuilder defaultEmailValidationExpression = new StringBuilder();
               defaultEmailValidationExpression.Append(UserModuleBase.GetSetting(base.PortalId, "Security_EmailValidation"));
               if (defaultEmailValidationExpression[0] == '^')
                  defaultEmailValidationExpression.Remove(0, 1);
               if (defaultEmailValidationExpression[defaultEmailValidationExpression.Length - 1] == '$')
                  defaultEmailValidationExpression.Remove(defaultEmailValidationExpression.Length - 1, 1);

               eMailAddressValidator.ValidationExpression = String.Format("^{0}(;{0}){1}$", defaultEmailValidationExpression, "{0,}");
               eMailAddressValidator.InvalidErrorMessage = Localization.GetString("EMailAddressValidator.InvalidErrorMessage", base.LocalResourceFile);
               eMailAddressValidator.RequiredErrorMessage = Localization.GetString("EMailAddressValidator.RequiredErrorMessage", base.LocalResourceFile);
               eMailAddressValidator.Required = this.SubmitByEMail;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void EMailFormatCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox eMailFormatCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               eMailFormatCheckBox.Text = Localization.GetString("EMailFormatCheckBox.Text", base.LocalResourceFile);
               eMailFormatCheckBox.Checked = (this.EMailFormat == MailFormat.Html);
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void SenderAddressDropDownList_Load(object sender, EventArgs e)
      {
         DropDownList senderAddressDropDownList = (DropDownList)sender;
         if (!(Page.IsPostBack))
         {
            ListItem li;
            try
            {
               // Add _the_ Portal Administrator
               li = new ListItem();
               li.Text = Localization.GetString("PortalAdministrator.Text", base.LocalResourceFile);
               li.Value = "[ADMIN]";
               senderAddressDropDownList.Items.Add(li);

               // Add all users from the admin Group
               RoleController rc = new RoleController();
               // string adminRoleName = rc.GetRole(base.PortalSettings.AdministratorRoleId, base.PortalId).RoleName;
               string adminRoleName = rc.GetRoleById(base.PortalId, base.PortalSettings.AdministratorRoleId).RoleName;
               // ArrayList admins = rc.GetUsersByRoleName(base.PortalId, adminRoleName);
               IList<UserInfo> admins = RoleController.Instance.GetUsersByRole(base.PortalId, adminRoleName);
               foreach (UserInfo user in admins)
               {
                  li = new ListItem();
                  li.Text = String.Format("{0} [A]", user.DisplayName);
                  li.Value = String.Format("[USERID]{0}", user.UserID);
                  senderAddressDropDownList.Items.Add(li);
               }

               // Add _the_ Host
               li = new ListItem();
               li.Text = Localization.GetString("Host.Text", base.LocalResourceFile);
               li.Value = "[HOST]";
               senderAddressDropDownList.Items.Add(li);

               // Add all super users
               
               ArrayList hostUsers = UserController.GetUsers(false, true, Null.NullInteger);
               foreach (UserInfo user in hostUsers)
               {
                  li = new ListItem();
                  li.Text = String.Format("{0} [H]", user.DisplayName);
                  li.Value = String.Format("[USERID]{0}", user.UserID);
                  senderAddressDropDownList.Items.Add(li);
               }

               // Finally, add all form items of the type EMailAddress (if any)
               foreach (FormItemInfo fii in this.TheForm)
               {

                  if (Helpers.IsItemEmailAddress(fii.FormItemType))
                  {
                     li = new ListItem();
                     li.Value = String.Format("[FORMITEM]{0}", fii.FormItemID);
                     li.Text = String.Format("{0} [F]", fii.FormItemLabel);
                     senderAddressDropDownList.Items.Add(li);
                  }
               }
               this.SenderAddressDropDownList.SelectedValue = this.SenderAddress;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ReplyToAddressDropDownList_Load(object ReplyTo, EventArgs e)
      {
         DropDownList ReplyToAddressDropDownList = (DropDownList)ReplyTo;
         if (!(Page.IsPostBack))
         {
            ListItem li;
            try
            {
               // Add the sender's address
               li = new ListItem();
               li.Text = Localization.GetString("SameAsSender.Text", base.LocalResourceFile);
               li.Value = "";
               ReplyToAddressDropDownList.Items.Add(li);


               // Add _the_ Portal Administrator
               li = new ListItem();
               li.Text = Localization.GetString("PortalAdministrator.Text", base.LocalResourceFile);
               li.Value = "[ADMIN]";
               ReplyToAddressDropDownList.Items.Add(li);

               // Add all users from the admin Group
               RoleController rc = new RoleController();
               // string adminRoleName = rc.GetRole(base.PortalSettings.AdministratorRoleId, base.PortalId).RoleName;
               string adminRoleName = rc.GetRoleById(base.PortalId, base.PortalSettings.AdministratorRoleId).RoleName;
               // ArrayList admins = rc.GetUsersByRoleName(base.PortalId, adminRoleName);
               IList<UserInfo> admins = RoleController.Instance.GetUsersByRole(base.PortalId, adminRoleName);
               foreach (UserInfo user in admins)
               {
                  li = new ListItem();
                  li.Text = String.Format("{0} [A]", user.DisplayName);
                  li.Value = String.Format("[USERID]{0}", user.UserID);
                  ReplyToAddressDropDownList.Items.Add(li);
               }

               // Add _the_ Host
               li = new ListItem();
               li.Text = Localization.GetString("Host.Text", base.LocalResourceFile);
               li.Value = "[HOST]";
               ReplyToAddressDropDownList.Items.Add(li);

               // Add all super users
               ArrayList hostUsers = UserController.GetUsers(false, true, Null.NullInteger);
               foreach (UserInfo user in hostUsers)
               {
                  li = new ListItem();
                  li.Text = String.Format("{0} [H]", user.DisplayName);
                  li.Value = String.Format("[USERID]{0}", user.UserID);
                  ReplyToAddressDropDownList.Items.Add(li);
               }

               // Finally, add all form items of the type EMailAddress (if any)
               foreach (FormItemInfo fii in this.TheForm)
               {

                  if (Helpers.IsItemEmailAddress(fii.FormItemType))
                  {
                     li = new ListItem();
                     li.Value = String.Format("[FORMITEM]{0}", fii.FormItemID);
                     li.Text = String.Format("{0} [F]", fii.FormItemLabel);
                     ReplyToAddressDropDownList.Items.Add(li);
                  }
               }
               this.ReplyToAddressDropDownList.SelectedValue = this.ReplyToAddress;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void IncludeIPAddressInEmailCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox includeIPAddressInEmailCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               includeIPAddressInEmailCheckBox.Text = Localization.GetString("IncludeIPAddressInEmailLabel.Text", base.LocalResourceFile);
               includeIPAddressInEmailCheckBox.Checked = this.IncludeIPAddressInEmail;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void RedirectURLControl_Load(object sender, EventArgs e)
      {
         UrlControl redirectURLControl = (UrlControl)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               redirectURLControl.UrlType = this.RedirectURLType;
               redirectURLControl.Url = this.RedirectURL;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void AutoApproveCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox autoApproveCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               autoApproveCheckBox.Text = Localization.GetString("AutoApproveCheckBox.Text", base.LocalResourceFile);
               autoApproveCheckBox.Checked = this.AutoApprove;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ThemeDropDownList_Load(object sender, EventArgs e)
      {
         DropDownList themeDropDownList = (DropDownList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               // Get Module Themes
               string themesDirectory = String.Format("{0}Themes", base.ControlPath);
               string[] themeDirectories = Directory.GetDirectories(Server.MapPath(themesDirectory));
               foreach (string themeDirectory in themeDirectories)
               {
                  string[] dirParts = themeDirectory.Split(new char[] { '\\' });
                  themeDropDownList.Items.Add(String.Format("{0} [M]", dirParts[dirParts.Length - 1]));
               }

               // GetPortalThemes
               string portalThemesDirectory = String.Format("{0}{1}helferlein\\helferlein_Form\\{2}", base.PortalSettings.HomeDirectoryMapPath, (base.PortalSettings.HomeDirectoryMapPath.EndsWith("\\") ? String.Empty : "\\"), Base.THEMES_FOLDER);
               if (Directory.Exists(portalThemesDirectory))
               {
                  string[] portalThemesDirectories = Directory.GetDirectories(portalThemesDirectory);
                  foreach (string portalThemeDirectory in portalThemesDirectories)
                  {
                     string[] dirParts = portalThemeDirectory.Split(new char[] { '\\' });
                     themeDropDownList.Items.Add(String.Format("{0} [P]", dirParts[dirParts.Length - 1]));
                  }
               }
               themeDropDownList.SelectedValue = this.Theme;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void WidthTextBox_Load(object sender, EventArgs e)
      {
         TextBox widthTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { widthTextBox.Text = this.Width.ToString(); }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void FormHeaderTemplateTextBox_Load(object sender, EventArgs e)
      {
         TextBox formHeaderTemplateTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { formHeaderTemplateTextBox.Text = this.FormHeaderTemplate; }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void FormItemTemplateTextBox_Load(object sender, EventArgs e)
      {
         TextBox formItemTemplateTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { formItemTemplateTextBox.Text = this.FormItemTemplate; }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void FormFooterTemplateTextBox_Load(object sender, EventArgs e)
      {
         TextBox formFooterTemplateTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { formFooterTemplateTextBox.Text = this.FormFooterTemplate; }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void LabelTemplateTextBox_Load(object sender, EventArgs e)
      {
         TextBox labelTemplateTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try { labelTemplateTextBox.Text = this.LabelTemplate; }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void RequiredFieldMarkerOptions_Load(object sender, EventArgs e)
      {
         RadioButtonList requiredFieldMarkerOptions = (RadioButtonList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               string[] requiredFieldMarkerTypeNames = Enum.GetNames(typeof(RequiredFieldMarkerType));
               Dictionary<int, string> requiredFieldMarkerTypeEntries = new Dictionary<int, string>();
               for (int i = 0; i < requiredFieldMarkerTypeNames.Length; i++)
                  requiredFieldMarkerTypeEntries.Add(Convert.ToInt32(Enum.GetValues(typeof(RequiredFieldMarkerType)).GetValue(i)), Localization.GetString("RequiredFieldMarkerType." + requiredFieldMarkerTypeNames[i], this.SharedResourceFile));
               requiredFieldMarkerOptions.DataSource = requiredFieldMarkerTypeEntries;
               requiredFieldMarkerOptions.DataTextField = "value";
               requiredFieldMarkerOptions.DataValueField = "key";
               requiredFieldMarkerOptions.DataBind();
               // This is not supported yet...
               requiredFieldMarkerOptions.Items.Remove(this.RequiredFieldMarkerOptions.Items[3]);
               requiredFieldMarkerOptions.Items.Remove(this.RequiredFieldMarkerOptions.Items[2]);

               requiredFieldMarkerOptions.Items[0].Text += "&nbsp;&nbsp;<img src=\"" + ResolveUrl("~/images/required.gif") + "\">";
               requiredFieldMarkerOptions.SelectedValue = this.RequiredFieldMarker.ToString();
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowRequiredFieldMarkerExplanationOptions_Load(object sender, EventArgs e)
      {
         RadioButtonList showRequiredFieldMarkerExplanationOptions = (RadioButtonList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               string[] whereToDisplayRequiredFieldMarkerExplanationNames = Enum.GetNames(typeof(ShowAdditionalItems));
               Dictionary<int, string> whereToDisplayRequiredFieldMarkerExplanation = new Dictionary<int, string>();
               for (int i = 0; i < whereToDisplayRequiredFieldMarkerExplanationNames.Length; i++)
                  whereToDisplayRequiredFieldMarkerExplanation.Add(Convert.ToInt32(Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(i)), Localization.GetString("ShowAdditionalItems." + whereToDisplayRequiredFieldMarkerExplanationNames[i], this.SharedResourceFile));
               showRequiredFieldMarkerExplanationOptions.DataSource = whereToDisplayRequiredFieldMarkerExplanation;
               showRequiredFieldMarkerExplanationOptions.DataTextField = "value";
               showRequiredFieldMarkerExplanationOptions.DataValueField = "key";
               showRequiredFieldMarkerExplanationOptions.DataBind();
               showRequiredFieldMarkerExplanationOptions.SelectedValue = Convert.ToString(Convert.ToInt32(this.WhereToDisplayRequiredFieldMarkerExplanation));
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void SubmitButtonOptions_Load(object sender, EventArgs e)
      {
         RadioButtonList submitButtonOptions = (RadioButtonList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               string[] submitButtonsNames = Enum.GetNames(typeof(SubmitButtonsAppearance));
               Dictionary<int, string> submitButtons = new Dictionary<int, string>();
               for (int i = 0; i < submitButtonsNames.Length; i++)
                  submitButtons.Add(Convert.ToInt32(Enum.GetValues(typeof(SubmitButtonsAppearance)).GetValue(i)), Localization.GetString("SubmitButtonsAppearance." + submitButtonsNames[i], this.SharedResourceFile));
               submitButtonOptions.DataSource = submitButtons;
               submitButtonOptions.DataTextField = "value";
               submitButtonOptions.DataValueField = "key";
               submitButtonOptions.DataBind();
               submitButtonOptions.SelectedValue = Convert.ToString(Convert.ToInt32(this.SubmitButtons));
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void CaptchaCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox captchaCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               captchaCheckBox.Text = Localization.GetString("CaptchaCheckBox.Text", base.LocalResourceFile);
               captchaCheckBox.Checked = this.Captcha;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void CaptchaCheckBox_CheckedChanged(object sender, EventArgs e)
      {
         CheckBox captchaCheckBox = (CheckBox)sender;
         if (captchaCheckBox.Checked)
         {
            this.UnauthenticatedUsersOnlyCheckBox.Checked = this.UnauthenticatedUsersOnly;
            this.UnauthenticatedUsersOnlyCheckBox.Enabled = true;
         }
         else
         {
            this.UnauthenticatedUsersOnlyCheckBox.Checked = false;
            this.UnauthenticatedUsersOnlyCheckBox.Enabled = false;
         }
      }

      protected void UnauthenticatedUsersOnlyCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox unauthenticatedUsersOnlyCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               unauthenticatedUsersOnlyCheckBox.Text = Localization.GetString("UnauthenticatedUsersOnlyCheckBox.Text", base.LocalResourceFile);
               if (this.Captcha)
               {
                  unauthenticatedUsersOnlyCheckBox.Checked = this.UnauthenticatedUsersOnly;
               }
               else
               {
                  unauthenticatedUsersOnlyCheckBox.Checked = false;
                  unauthenticatedUsersOnlyCheckBox.Enabled = false;
               }
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ValidationDisplays_Load(object sender, EventArgs e)
      {
         CheckBoxList validationDisplays = (CheckBoxList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               validationDisplays.Items[0].Text = Localization.GetString("ShowSummary.Text", base.LocalResourceFile);
               validationDisplays.Items[1].Text = Localization.GetString("ShowMessageBox.Text", base.LocalResourceFile);
               validationDisplays.Items[0].Selected = this.ValidationShowSummary;
               validationDisplays.Items[1].Selected = this.ValidationShowMessageBox;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowApprovedSubmissionsOptions_Load(object sender, EventArgs e)
      {
         RadioButtonList showApprovedSubmissionsOptions = (RadioButtonList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               string[] whereToDisplayApprovedSubmissionsNames = Enum.GetNames(typeof(ShowAdditionalItems));
               Dictionary<int, string> whereToDisplayApprovedSubmissions = new Dictionary<int, string>();
               for (int i = 0; i < whereToDisplayApprovedSubmissionsNames.Length; i++)
                  whereToDisplayApprovedSubmissions.Add(Convert.ToInt32(Enum.GetValues(typeof(ShowAdditionalItems)).GetValue(i)), Localization.GetString("ShowAdditionalItems." + whereToDisplayApprovedSubmissionsNames[i], this.SharedResourceFile));
               showApprovedSubmissionsOptions.DataSource = whereToDisplayApprovedSubmissions;
               showApprovedSubmissionsOptions.DataTextField = "value";
               showApprovedSubmissionsOptions.DataValueField = "key";
               showApprovedSubmissionsOptions.DataBind();
               showApprovedSubmissionsOptions.SelectedValue = Convert.ToString(Convert.ToInt32(this.WhereToDisplayApprovedSubmissions));
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void KeepDaysTextBox_Load(object sender, EventArgs e)
      {
         TextBox keepDaysTextBox = (TextBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               if (this.KeepDays != null)
                  this.KeepDaysTextBox.Text = this.KeepDays.ToString();
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void GroupOutputByDropDownList_Load(object sender, EventArgs e)
      {
         DropDownList groupOutputByDropDownList = (DropDownList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               groupOutputByDropDownList.Items[0].Text = Localization.GetString("None_Specified.Text");
               if (this.GroupOutputByItems.Count == 0)
               {
                  groupOutputByDropDownList.Visible = false;
               }
               else
               {
                  groupOutputByDropDownList.AppendDataBoundItems = true;
                  groupOutputByDropDownList.DataSource = this.GroupOutputByItems;
                  groupOutputByDropDownList.DataValueField = "key";
                  groupOutputByDropDownList.DataTextField = "value";
                  groupOutputByDropDownList.DataBind();
                  groupOutputByDropDownList.SelectedValue = this.GroupOutputByItem;
               }
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void NoGroupableFormItemsDefinedLabel_Load(object sender, EventArgs e)
      {
         Label noGroupableFormItemsDefinedLabel = (Label)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               noGroupableFormItemsDefinedLabel.Text = Localization.GetString("NoGroupableFormItemsDefinedLabel.Text", base.LocalResourceFile);
               if (this.GroupOutputByItems.Count == 0)
                  noGroupableFormItemsDefinedLabel.Visible = true;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void RenderAsHeadlineDropDownList_Load(object sender, EventArgs e)
      {
         DropDownList renderAsHeadlineDropDownList = (DropDownList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               renderAsHeadlineDropDownList.Items[0].Text = Localization.GetString("None_Specified.Text");
               if (this.RenderAsHeadlineItems.Count == 0)
               {
                  renderAsHeadlineDropDownList.Visible = false;
               }
               else
               {
                  renderAsHeadlineDropDownList.AppendDataBoundItems = true;
                  renderAsHeadlineDropDownList.DataSource = this.RenderAsHeadlineItems;
                  renderAsHeadlineDropDownList.DataValueField = "key";
                  renderAsHeadlineDropDownList.DataTextField = "value";
                  renderAsHeadlineDropDownList.DataBind();
                  renderAsHeadlineDropDownList.SelectedValue = this.RenderAsHeadlineItem;
               }
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void RenderAsHeadlineDropDownList_SelectedIndexChanged(object sender, EventArgs e)
      {
         DropDownList renderAsHeadlineDropDownList = (DropDownList)sender;
         this.UseHeadlineAsSubjectPanel.Visible = (renderAsHeadlineDropDownList.SelectedIndex > 0);
      }

      protected void NoRenderableAsHeadlineFormItemsDefinedLabel_Load(object sender, EventArgs e)
      {
         Label noRenderableAsHeadlineFormItemsDefinedLabel = (Label)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               noRenderableAsHeadlineFormItemsDefinedLabel.Text = Localization.GetString("NoRenderableAsHeadlineFormItemsDefinedLabel.Text", base.LocalResourceFile);
               if (this.RenderAsHeadlineItems.Count == 0)
                  noRenderableAsHeadlineFormItemsDefinedLabel.Visible = true;

            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void UseHeadlineAsSubjectCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox useHeadlineAsSubjectCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               useHeadlineAsSubjectCheckBox.Checked = this.UseHeadlineAsSubject;
               UseHeadlineAsSubjectPanel.Visible = ((this.RenderAsHeadlineItems.Count > 0) && (this.RenderAsHeadlineDropDownList.SelectedIndex > 0) && (this.SendModes.Items[0].Selected));
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void HeadlineAlignmentRadioButtonList_Load(object sender, EventArgs e)
      {
         RadioButtonList headlineAlignmentRadioButtonList = (RadioButtonList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               headlineAlignmentRadioButtonList.Items[0].Text = Localization.GetString("Left.Text");
               headlineAlignmentRadioButtonList.Items[1].Text = Localization.GetString("Center.Text");
               headlineAlignmentRadioButtonList.Items[2].Text = Localization.GetString("Right.Text");
               headlineAlignmentRadioButtonList.SelectedValue = (this.HeadlineAlignment == "Left" ? string.Empty : this.HeadlineAlignment);
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowDateCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox showDateCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               showDateCheckBox.Text = Localization.GetString("ShowDateCheckBox.Text", base.LocalResourceFile);
               showDateCheckBox.Checked = this.ShowDate;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowFlagCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox showFlagCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               showFlagCheckBox.Text = Localization.GetString("ShowFlagCheckBox.Text", base.LocalResourceFile);
               showFlagCheckBox.Checked = this.ShowFlag;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowLabelsCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox showLabelsCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               showLabelsCheckBox.Text = Localization.GetString("ShowLabelsCheckBox.Text", base.LocalResourceFile);
               showLabelsCheckBox.Checked = this.ShowLabels;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void ShowRecipientCheckBox_Load(object sender, EventArgs e)
      {
         CheckBox showRecipientCheckBox = (CheckBox)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               showRecipientCheckBox.Text = Localization.GetString("ShowRecipientCheckBox.Text", base.LocalResourceFile);
               showRecipientCheckBox.Checked = this.ShowRecipient;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void AddToDropDownListDropDownList_Load(object sender, EventArgs e)
      {
         DropDownList addToDropDownListDropDownList = (DropDownList)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               addToDropDownListDropDownList.Items[0].Text = Localization.GetString("None_Specified.Text");
               if (this.AddToDropDownListItems.Count == 0)
               {
                  addToDropDownListDropDownList.Visible = false;
               }
               else
               {
                  addToDropDownListDropDownList.AppendDataBoundItems = true;
                  addToDropDownListDropDownList.DataSource = this.AddToDropDownListItems;
                  addToDropDownListDropDownList.DataValueField = "key";
                  addToDropDownListDropDownList.DataTextField = "value";
                  addToDropDownListDropDownList.DataBind();
                  addToDropDownListDropDownList.SelectedValue = this.AddToDropDownListItem;
               }
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }

      protected void NoAppendableFormItemsDefinedLabel_Load(object sender, EventArgs e)
      {
         Label noAppendableFormItemsDefinedLabel = (Label)sender;
         if (!(Page.IsPostBack))
         {
            try
            {
               noAppendableFormItemsDefinedLabel.Text = Localization.GetString("NoAppendableFormItemsDefinedLabel.Text", base.LocalResourceFile);
               if (this.AddToDropDownListItems.Count == 0)
                  noAppendableFormItemsDefinedLabel.Visible = true;
            }
            catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); }
         }
      }
#endregion

#region Update Methods
      private void UpdateAquarium(string locale)
      {
         string s;
         if (this.Aquarium.TryGetValue("ModuleTitle." + locale, out s))
            this.Aquarium["ModuleTitle." + locale] = HtmlUtils.StripTags(this.ModuleTitleTextBox.Text, false).Trim();
         else
            this.Aquarium.Add("ModuleTitle." + locale, HtmlUtils.StripTags(this.ModuleTitleTextBox.Text, false).Trim());
         if (this.Aquarium.TryGetValue("Subject." + locale, out s))
            this.Aquarium["Subject." + locale] = HtmlUtils.StripTags(this.SubjectTextBox.Text, false).Trim();
         else
            this.Aquarium.Add("Subject." + locale, HtmlUtils.StripTags(this.SubjectTextBox.Text, false).Trim());
      }

      private void UpdateBooleanSetting(string setting, bool settingValue)
      {
         if (base.Settings[setting] == null)
         {
            if (settingValue)
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue.ToString());
         }
         else
         {
            if (settingValue)
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue.ToString());
            else
               Controller.DeleteModuleSetting(base.ModuleId, setting);
         }
      }

      private void UpdateTextSetting(string setting, string settingValue)
      {
         if (base.Settings[setting] == null)
         {
            if (!(String.IsNullOrEmpty(settingValue)))
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue);
         }
         else
         {
            if (!(String.IsNullOrEmpty(settingValue)))
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue);
            else
               Controller.DeleteModuleSetting(base.ModuleId, setting);
         }
      }

      private void UpdateIntegerSetting(string setting, int? settingValue)
      {
         if (base.Settings[setting] == null)
         {
            if (settingValue != null)
            {
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue.ToString());
            }
         }
         else
         {
            if (settingValue != null)
               Controller.UpdateModuleSetting(base.ModuleId, setting, settingValue.ToString());
            else
               Controller.DeleteModuleSetting(base.ModuleId, setting);
         }
      }

      private Unit? UnitParser(string unitValue)
      {
         Unit? result;
         try
         {
            result = Unit.Parse(unitValue);
         }
         catch (Exception ex)
         {
            Exceptions.LogException(ex);
            result = null;
         }
         return result;
      }

      private int? Int32Parser(string value)
      {
         int? result;
         Int32 int32val;
         bool isInt32;
         try
         {
            isInt32 = Int32.TryParse(value, out int32val);
            if (isInt32)
               result = int32val;
            else
               result = null;
         }
         catch (Exception ex)
         {
            Exceptions.LogException(ex);
            result = null;
         }
         return result;
      }
#endregion
   }
}
